package com.zr.service.car.Impl

import com.github.pagehelper.PageHelper
import com.zr.mapper.car.CarMapper
import com.zr.service.car.CarServer
import com.zr.util.TokenInterceptor
import com.zr.util.TokenUtil
import com.zr.vo.car.Car
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.web.multipart.MultipartFile
import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.util.*
import javax.annotation.Resource

@Service
class CarServerImpl :CarServer{

    @Resource
    val carMapper: CarMapper?=null
    @Autowired
    val tokenUtil:TokenUtil?=null
    override fun listCarsByCar(car: Car): MutableList<Car>? {
        //使用分页插件按照浏览器传过来的参数对查询结果进行分页显示
        PageHelper.startPage<Any>(car.pageNum, car.pageSize)
        return carMapper?.listCarsByCar(car)
    }

    override fun add(car: Car) {
        car.createTime= Date()
        car.createId=tokenUtil?.userId
        carMapper?.insertSelective(car)
    }

    override fun deleteByCar(car: Car) {
        carMapper?.deleteByPrimaryKey(car.id)
    }

    override fun edit(car: Car) {
        car.modifyTime=Date()
        car.modifyId=tokenUtil?.userId
        carMapper?.updateByPrimaryKeySelective(car)
    }

    override fun uploadCarImg(file: MultipartFile) {
        val extensionName=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        val path="C:\\Users\\86138\\Desktop\\uploadImg\\" + UUID.randomUUID().toString() + extensionName;
        val imgFile= File(path)
        file.transferTo(imgFile)
        val car=carMapper?.selectByPrimaryKey(TokenInterceptor.sharedRequest.getHeader("SelectedCarId").toLong())
        car?.imgUrl=path
        carMapper?.updateByPrimaryKeySelective(car)
    }

    override fun loadImg(car: Car): String? {
        if(car?.imgUrl.isNullOrEmpty()) return null
        val file=File(car?.imgUrl)
        println("汽车图片的路径是：$file")
        if (file.exists()){
            var b: ByteArray? = null
            try {
                FileInputStream(file).use { fis ->
                    b = ByteArray(file.length().toInt())
                    fis.read(b)
                }
            } catch (e: IOException) {
                e.printStackTrace()
            }
            return Base64.getEncoder().encodeToString(b)
        }
        return null
    }
}